<%@ page contentType="text/html; charset=UTF-8"%>
<%@page import="com.sinodata.bsm.common.vo.ResPauseRule"%>
<%@page import="java.util.List"%>
<%@page import="com.sinodata.bsm.common.constants.ResConstants"%>
<%@page import="org.quartz.CronExpression"%>
<%@page import="java.util.Date"%>
<%@page import="com.sinodata.bsm.common.vo.Res"%>
<%@page import="com.sinodata.bsm.common.utils.DateUtil"%>
<%@page import="com.sinodata.bsm.common.utils.CrontabUtil"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="com.sinodata.bsm.center.purview.FunctionConstants"%>
<%@ page import="com.sinodata.bsm.center.purview.UserFunctionValidate"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%
	List<ResPauseRule> pauseRules = (List<ResPauseRule>)request.getAttribute("pauseRules");
	Res res = (Res)request.getAttribute("res");
	ResPauseRule pause = (ResPauseRule)request.getAttribute("pauseRule");
 %>
<html>
  <head>
    <title>资源暂停</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="pragma" content="no-cache"/>
	<meta http-equiv="cache-control" content="no-cache"/>
	<meta http-equiv="expires" content="0"/> 
	<%@ include file="../include/common.jsp"%>
	<%@ include file="../include/table.jsp"%>
	<%@ include file="../include/jbox.jsp"%>
	<style type="text/css">
		.tdValue{
			border: 1px solid #e7e6e7;
			line-height: 26px;
			height: 32px;
			padding-left: 5px;
			overflow: hidden;
		}
	</style>
	<script type="text/javascript" >
		$(document).ready(function(){
			$("#pauseRules").dataTable({
				"bProcessing": true, 
				"bServerSide": true,
				"sServerMethod": 'POST',
				"sAjaxSource":'res-pause!list.action?resId=${res.id}',
				"bPaginate":false,
				"bSort": true,
				"bFilter":false,
				"sPaginationType": 'full_numbers',
				"aoColumns":[
				<%if(UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER)){%>
					{"mDataProp":"operate","bSortable": false,"fnCreatedCell":function(nTd, sData, oData, iRow, iCol){
						$(nTd).html("<a href='#"+oData.id+"' onclick='openUpdateWindow("+oData.id+")'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;&nbsp;<a href='#"+oData.id+"' onclick='del("+oData.id+")'><img src='../style/default/bsm/images/delete.gif' title='删除' /></a>");
					}},
					<%} %>
					{"mDataProp":"type","bSortable": false},
					{"mDataProp":"rule","bSortable": false},
					{"mDataProp":"id","bVisible":false}
				],
				"oLanguage":{
					"sZeroRecords": "没有找到记录",
					"sInfo":"共找到 _TOTAL_ 条记录",
					"sInfoEmpty": ""
				}
			});
			
		});
		
		function openInputWindow(){
			var url ='iframe:resource/res-pause!input.action';
		    var opt =  {title:'添加暂停规则',id:'inputPauseRule',width:400,height:200,iframeScrolling:'no',submit:function(v, h, f){},buttons:{}};
		    getTopWin(window).openjBox(url,opt,'inputPauseRuleWindow',window);
		}
		
		//添加暂停规则
		savePauseRule = function(pauseRule){
			pauseRule.resId='${res.id}';
			 $.ajax({
					type:'post',
					url:'res-pause!save.action',
					data:pauseRule,
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
						var oTable =$('#pauseRules').dataTable();
						getTopWin(window).getMessageBox().tip('操作成功。', 'success'); 
						window.location.reload();
					},
					error:function(){
						getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
					}
			});
			
		}
		
		//删除
		function del(id){
			if(isDel(id)==true){
				getTopWin(window).getMessageBox().alert('暂停规则已被删除,编号为:'+id,'错误');
				return;
			}
		
			var submit = function(v, h, f){
			  	if (v == 'ok'){
			  		getTopWin(window).getMessageBox().tip("正在删除暂停规则...", 'loading');
					$.ajax({
							type:'post',
							url:'res-pause!delete.action',
							data:{id:id},
							global:false,
							async:false,
							cache:false,
							dataType:'json',
							success:function(data,textStatus){
								var oTable =$('#pauseRules').dataTable();
								window.setTimeout(function () {
										getTopWin(window).getMessageBox().tip('暂停规则删除成功。', 'success');  
										window.location.reload();
								},1500);
								
							},
							error:function(){
								getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
							}
					});
			  	}
			}
			getTopWin(window).getMessageBox().confirm('确定删除?','提示',submit);
		}
		
		//修改
		function openUpdateWindow(pauseId){
			if(isDel(pauseId)==true){
				getTopWin(window).getMessageBox().alert('暂停规则已被删除,编号为:'+pauseId,'错误');
				return;
			}
		
			var url ='iframe:resource/res-pause!initUpdate.action?id='+pauseId+'';
		    var opt =  {title:'修改暂停规则',id:'inputPauseRule',width:400,height:200,iframeScrolling:'no',submit:function(v, h, f){},buttons:{}};
		    getTopWin(window).openjBox(url,opt,'inputPauseRuleWindow',window);
		}
		
		//恢复监控
		function reduction(){
			var submit = function(v, h, f){
			  	if (v == 'ok'){
					getTopWin(window).getMessageBox().tip("正在恢复监控...", 'loading');
					$.ajax({
							type:'post',
							url:'res-pause!resume.action',
							data:{resId:'${res.id}'},
							global:false,
							async:false,
							cache:false,
							dataType:'json',
							success:function(data,textStatus){
								window.setTimeout(function () {
										getTopWin(window).getMessageBox().tip('恢复监控成功。', 'success');  
										window.location.reload();
								},1500);
								
							},
							error:function(){
								getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
							}
					});		  	
			  	}
			 }
			getTopWin(window).getMessageBox().confirm('确定恢复?','提示',submit);
		}
		
		//完全暂停
		function completePause(){
			var submit = function(v, h, f){
			  	if (v == 'ok'){
					getTopWin(window).getMessageBox().tip("正在暂停...", 'loading');
					$.ajax({
							type:'post',
							url:'res-pause!completePause.action',
							data:{resId:'${res.id}'},
							global:false,
							async:false,
							cache:false,
							dataType:'json',
							success:function(data,textStatus){
								window.setTimeout(function () {
										getTopWin(window).getMessageBox().tip('暂停成功。', 'success');  
										window.location.reload();
								},1500);
								
							},
							error:function(){
								getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
							}
					});		  	
			  	}
			 }
			getTopWin(window).getMessageBox().confirm('确定暂停?','提示',submit);
		}
		
		//验证是否删除
		function isDel(id){
			var isFlag = false;
			$.ajax({
					type:'post',
					url:'res-pause!isDelete.action',
					data:{id:id},
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
						isFlag = data;
					},
					error:function(){
						getTopWin(window).getMessageBox().alert('检验暂停规则是否删除出错!','错误');
					}
			});
			return isFlag;
		}
	</script>
  </head>
  
  <body>
  	<h2 class="title-h2"><span><img src="${pageContext.request.contextPath}/style/default/bsm/images/arrow-down.gif"/></span>资源监控状态</h2>
	<div id="topDiv" >
		<table class="table_eidt" >
			<tbody>
	    		<tr>
	    			<td class="td_left" style="width:180px;" >资源当前监控状态</td>
	    			<td class="tdValue" >
	    				<span style="padding-left:5px;">
	    					<%
	    						  Long currentDate = System.currentTimeMillis(); //当前时间 
	    						 Long tempDate = null;		 //最终显示的 恢复暂停时间
	    						 Long nearestDate =  null;    // 正常监控下，下一次监控时间
	    						 StringBuffer str = new StringBuffer("");
	    						 for(int i=0;pauseRules!=null&&i<pauseRules.size();i++){
	    						 	ResPauseRule pauseRule = pauseRules.get(i);
	    						 	if(pauseRule.getType().intValue()==ResConstants.RES_PAUSE_TYPE_CYC){ //周期暂停
	    						 		CronExpression cron = new CronExpression(pauseRule.getRule().split("@")[0]);
	    						 		Date date = cron.getNextValidTimeAfter(new Date());

	    						 		long time = date.getTime()+(Long.parseLong(pauseRule.getRule().split("@")[1]) * 1000);
	    						 		if(date.getTime()>currentDate){
	    						 			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	    						 			SimpleDateFormat format1 = new SimpleDateFormat("HH:mm:ss");
	    						 			time = format.parse(DateUtil.format(new Date(),"yyyy-MM-dd ")+format1.format(date)).getTime()+(Long.parseLong(pauseRule.getRule().split("@")[1]) * 1000);
	    						 		}
	    						 		
	    						 		//判断设置的暂停时间范围 是否是现在时间
	    						 		if(tempDate==null){
	    						 			tempDate = time;
	    						 			if(time>=currentDate){
	    						 				nearestDate = date.getTime();
	    						 			}
	    						 		}else{
	    						 			if(time>=tempDate&&time>=currentDate){  //找到设置的暂停时间 离当前时间最近的一个 判断为是否在监控
	    						 				//out.println(new Date(time).toLocaleString()+"--->"+new Date(tempDate).toLocaleString());
	    						 				tempDate = time;
	    						 			}
	    						 			if(nearestDate!=null&&date.getTime()<=nearestDate&&date.getTime()>=currentDate){
	    						 				nearestDate= date.getTime();
	    						 			}
	    						 		}
	    						 		
	    						 	}else if(pauseRule.getType().intValue()==ResConstants.RES_PAUSE_TYPE_TIM){ //定时暂停
	    						 		String[] rules   = pauseRule.getRule().split("@");
	    						 		String start = rules[0];
	    						 		
	    						 		if(rules.length>1){ //可能未设置结束暂停时间
	    						 		  	String end = rules[1];
	    						 		  	if(tempDate==null){
	    						 		  		if(Long.parseLong(end)>=currentDate){
	    						 		  	    	tempDate = Long.parseLong(end);
	    						 		  	    }
	    						 		  	}else{
	    						 		  		if(Long.parseLong(start)<=tempDate&&Long.parseLong(end)>=tempDate&&Long.parseLong(end)>currentDate){
	    						 		  			tempDate = Long.parseLong(end);
	    						 		  		}
	    						 		  	}
	    						 		  	
	    						 		  	if(nearestDate==null){
	    						 		  		if(Long.parseLong(start)>=currentDate){
	    						 		  			nearestDate = Long.parseLong(start);
	    						 		  		}
	    						 		  	}else{
	    						 		  		
	    						 		  		if(nearestDate!=null&&Long.parseLong(start)<nearestDate&&Long.parseLong(start)>=currentDate){
	    						 		  			nearestDate= Long.parseLong(start);
	    						 		  		}
	    						 		  	}
	    						 		  	
	    						 		 
	    						 		}else{
	    						 			tempDate= Long.parseLong("0");
	    						 		}
	    						 		
	    						 	}else{
	    						 		tempDate= Long.parseLong("0");
	    						 		str.append("<span style='color:red;'>已暂停,未设置监控恢复时间</span>");
	    						 		break;
	    						 	}
	    						 	
	    						 	if(i==(pauseRules.size()-1)){
	    						 		
	    						 		 if(tempDate!=null){
	    						 		 //,至"+new Date(tempDate).toLocaleString()+"后恢复监控
	    						 			str.append("<span style='color:red;'>已暂停</span>");
	    						 		}
	    						 	}
	    						 }
	    						 
	    						 if(pause!=null){
	    						 	out.println(str.toString());
	    						 }else{
	    						 	/*	if(nearestDate==null){
	    						 			statuValue = "正常监控";
	    						 		}else{
	    						 			statuValue = "正常监控,下次暂停时间为"+new Date(nearestDate).toLocaleString();
	    						 		}*/
	    						    	out.println("正常监控");
	    						 }	
	    						
	    					 %>
	    				</span>
	    			</td>
	    		</tr>
	    	</tbody>
		</table>
	</div>
	
	<h2 class="title-h2"><span><img src="${pageContext.request.contextPath}/style/default/bsm/images/arrow-down.gif"/></span>资源暂停规则列表</h2>
	<div id="mainDiv" >
	<%if(UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER)){%>
		<div class ="toolbar" id="toolbar" >
  				<a href="javascript:;" onclick="openInputWindow()"  class="page_add" >添加暂停规则</a>
  		</div>
  		<%} %>
  		<table width="100%"  id="pauseRules" cellpadding="0" cellspacing="0" border="0" class="display" >
  			<thead>
    	 		<tr>
    	 		<%if(UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER)){%>
    	 			<th width="50px" >操作</th>
    	 			<%} %>
    	 			<th >暂停方式</th>
    	 			<th>暂停规则描述</th>
    	 		</tr>
    	 	</thead>
  		</table>
	</div>
  </body>
</html>
